#!/usr/bin/python
#-*- coding:utf-8 -*-

# persona_age.py
#
# Copyright (c) 2008 Marcelo Lira dos Santos
#
# Author: Marcelo Lira dos Santos <setanta@gmail.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation; either version 2 of
# the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA

import pygtk
pygtk.require('2.0')
import gtk
import gtk.glade
import random
from os.path import join

import data

class PersonaAge:

    CURRENT_YEAR = 1500
    MIN = 0
    MAX = 1

    def __init__(self, wtree, store, pixbufpath):
        self.age_range = None

        self.current_year = PersonaAge.CURRENT_YEAR
        self.timeline = store.get_timeline()

        self.age_hs = wtree.get_widget('age_hscale')

        dice_image = wtree.get_widget('dice_age_img')
        dice_image.set_from_file(join(pixbufpath, 'dice.png'))

        # Timeline View
        self.timeline_textview = wtree.get_widget('timeline_textview')
        self.timeline_textbuffer = gtk.TextBuffer()
        self.timeline_textview.set_buffer(self.timeline_textbuffer)

        wtree.signal_autoconnect(self)


    # Callbacks ---------------------------------------------------------------
    def on_hw_scale_value_changed(self, widget):
        self.update()

    def on_random_age_button_clicked(self, widget):
        if self.age_range is None:
            return
        min_age, max_age = self.age_range
        old_age = age = int(self.age_hs.get_value())
        while (old_age == age):
            age = random.randint(min_age, max_age)
        self.age_hs.set_value(age)

    def on_age_hscale_value_changed(self, widget):
        self.update()


    # Class Methods -----------------------------------------------------------
    def reset(self, age_range, age):
        lower, upper = age_range
        adj = gtk.Adjustment(age, lower, upper, 1)
        self.age_hs.set_adjustment(adj)
        self.age_range = (lower, upper)
        self.update()

    def get_age(self, age):
        return int(self.age_hs.get_value())

    def update(self):
        year = self.current_year - self.age_hs.get_value()
        try:
            event = '\n%s' % self.timeline[year]
        except KeyError:
            event = ''
        self.timeline_textbuffer.set_text('Nascido em %d D.C.%s' % \
                                          (year, event))

